package com.fyyg.common.exceptions;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.google.common.base.Strings;

public class StandardException extends RuntimeException{

	/**
	 * 
	 */
	private static final long serialVersionUID = 6538523361400239196L;

	/**
	 * 异常编码
	 */
	private String code;

	/**
	 * 关健数据
	 */
	private Map<String, String> keyword;
	
	private String localizeMessage;

	public enum Level {
		customer, customerService, developer
	}

	@Override
	public String getLocalizedMessage() {
		if (Strings.isNullOrEmpty(localizeMessage)) {
			return super.getLocalizedMessage();
		}

		return localizeMessage;
	}

	@Override
	public String toString() {
		String lm = getLocalizedMessage();
		String m = getMessage();
		StringBuffer sb = new StringBuffer();
		sb.append(getClass().getName() + ", ");
		
		if(StringUtils.equals(m, lm)){
			sb.append(m);
		}else{

			if (!Strings.isNullOrEmpty(m)) {
				sb.append(", " + m);
			}
			if (!Strings.isNullOrEmpty(lm)) {
				sb.append(", " + lm);
			}
		}
		

		return sb.toString();
	}

	public StandardException(String code, String message, Throwable cause) {
		super(message == null ? StringUtils.EMPTY : message, cause);
		this.code = code;
		this.keyword = new LinkedHashMap<String, String>();
	}

	public StandardException(String code, String message,
			String localizeMessage, Throwable cause) {
		super(message == null ? StringUtils.EMPTY : message, cause);
		this.code = code;
		this.keyword = new LinkedHashMap<String, String>();
		this.localizeMessage = localizeMessage;
	}

	public StandardException(Level level, String message,
			String localizeMessage, Throwable cause) {
		super(message == null ? StringUtils.EMPTY : message, cause);
		if (level != null) {
			this.code = level.name();
		}
		this.keyword = new LinkedHashMap<String, String>();
		this.localizeMessage = localizeMessage;
	}

	public StandardException(Level level, String message, Throwable cause) {
		super(message == null ? StringUtils.EMPTY : message, cause);
		if (level != null) {
			this.code = level.name();
		}
		this.keyword = new LinkedHashMap<String, String>();
	}

	public StandardException appendKeywords(String key, String word) {
		if (key != null) {
			keyword.put(key, word);
		}

		return this;
	}

	public String getCode() {
		return code;
	}

	public String getKeyword(String key) {
		return keyword.get(key);
	}

	public Map<String, String> getKeywords() {
		return keyword;
	}

	public List<String> getKeywordValues() {
		return new ArrayList<String>(keyword.values());
	}
}
